<?php
namespace Home\Controller;
/**
 * Created by PhpStorm.
 * User: yhg97p
 * Date: 2016/4/6
 * Time: 21:14
 */
class PayController extends \Think\Controller
{
    /**
     * 支付回调接口
     */
    public function nineteenPay()
    {
        $data = array();
        $data['info'] = json_encode($_REQUEST);
        $data['create_time'] = date("Y-m-d H:i:s");
        $data['ip'] = $_SERVER['REMOTE_ADDR'];
        $callback = M("CallbackParam")->add($data);
        if ($_REQUEST['json']) {
            $json = $_REQUEST['json'];
            $json = json_decode($json, true);
            $orderSno = $json['order_no'];
        } else {
            $orderSno = $_REQUEST['out_trade_no'];
        }
        $Invest = M("Invest");
        $InvestInfo = $Invest->where(array("order_no" => $orderSno, "status" => '2'))->find();//获取待付款的订单
        if ($InvestInfo) {
            if ($_REQUEST['trade_status'] && $_REQUEST['trade_status'] != "TRADE_SUCCESS") {
                return;
            }
            $data = array();
            $data['paysucess'] = '1';
            $data['status'] = "3";
            $Invest->where(array('order_no' => $orderSno))->save($data);
        } else {
            $Invest->where(array('order_no' => $orderSno))->save(array('paysuccess' => '2'));
        }
        $this->ajaxReturn(array('error' => 0, 'info' => "执行成功"));
    }

    //支付回调接口
    public function paycallback()
    {

        $param = I('params');
        $invest_id = $param['invest_id'];
        //判断订单是否已经支付
        $InvestInfo = M("Invest")->where(array("id" => $invest_id, "status" => '3'))->find();
        if ($InvestInfo) {
            $coupon_id = $param['coupon_id'];
            $orderSno = $InvestInfo['order_no'];
            if ($coupon_id) {
                M("UserCoupon")->where(array("id" => $coupon_id))->save(array("status" => 2, "order_no" => $orderSno));
            }
            $grouporderid = $param['grouporderid'];
            $type = $param['type'];
            if ($type == 2) {
                $res = $this->addGroupOrder($grouporderid, $invest_id);
                if($res==1){
                    $this->ajaxReturn(array('error' => 1, 'info' => "人数已经满了,该订单已经失效，进入退款状态"));
                }
            }
        }
        $this->ajaxReturn(array('error' => 0, 'info' => "执行成功"));
    }

    //发起团购订单
    public function addGroupOrder($grouporderid, $orderid)
    {
        if ($grouporderid) {//如果存在团购id 判断为加入订单
            //判断这个团是否存在 并且人数没有超过上限
            $invested = M("Invest")->where(array("id" => $orderid))->find();
            $data = array();
            $data['sub_order_id'] = $orderid;
            $data['sub_user_id'] = $invested['user_id'];
            $data['create_time'] = date("Y-m-d H:i:s");
            $data['grouporderid'] = $grouporderid;
            M("GroupOrderList")->add($data);
            //如果团人数满了状态改成2
            $grouporderinfo = M("GroupOrder")->where(array("id" => $grouporderid))->find();
            $join_count = $grouporderinfo['join_count'];
            $clusters =  $grouporderinfo['clusters'];
            if($clusters == $join_count){
                //将订单改成11 失效状态
                M("Invest")->where(array("id"=>$orderid))->save(array("status"=>'11'));
                return 1;//人数已经满了
            }elseif($join_count+1==$clusters){//最后一个
                M("GroupOrder")->where(array("id" => $grouporderid))->save(array("join_count" => array('exp', 'join_count+1'),"status"=>'2'));
            }else{
                M("GroupOrder")->where(array("id" => $grouporderid))->save(array("join_count" => array('exp', 'join_count+1')));
            }
        } else {
            //根据group_id获取对应的团购结束时间
            $activeGroup = M()->query("SELECT a.user_id,b.`goods_id`,c.`group_id`,d.`cycle`,d.`clusters` FROM mt_invest a
                                        LEFT JOIN mt_invest_goods b ON a.id=b.invest_id
                                        LEFT JOIN mt_group_goods c ON c.goods_id=b.`goods_id`
                                        LEFT JOIN mt_active_group d ON c.`group_id`=d.`id`
                                        WHERE a.`id`='$orderid';")[0];

            $endtime = ($activeGroup['cycle'] * 60) + time();
            $data = array();
            $data['parent_order_id'] = $orderid;
            $data['parent_user_id'] = $activeGroup['user_id'];
            $data['join_count'] = 1;
            $data['status'] = 1;
            $data['goods_id'] = $activeGroup['goods_id'];
            $data['group_id'] = $activeGroup['group_id'];
            $data['clusters'] = $activeGroup['clusters'];//成团人数
            $data['end_time'] = date("Y-m-d H:i:s", $endtime);
            $data['create_time'] = date("Y-m-d H:i:s");
            M("GroupOrder")->add($data);
        }
    }
    public function wxserver()
    {
        require_once(dirname(dirname(dirname(__FILE__))) . '/Notify/wx/wxcontroller.php');
        $wecontroller = new wecontroller();
        $wecontroller->server();
    }
    //权限回调
    public function authcallback()
    {
        require_once(dirname(dirname(dirname(__FILE__))) . '/Notify/wx/wxcontroller.php');
        $wecontroller = new wecontroller();
        $wecontroller->oauthcallback();
        $targetUrl = "http://weixin.ihanghang.com/index.php?s=/Home/share/index.html";
        header('location:' . $targetUrl);
    }
    /**
     * 微信支付回调接口
     */
    public function wxPay()
    {
        $data = array();
        $data['info'] = json_encode($_REQUEST);
        $data['create_time'] = date("Y-m-d H:i:s");
        $data['ip'] = $_SERVER['REMOTE_ADDR'];
        $callback = M("CallbackParam")->add($data);
        require_once(dirname(dirname(dirname(__FILE__))) . '/Notify/wx/pay.php');
        $wechatpay = new wechatpay();
        $wechatpay->payback();
    }

    //微信支付
    public function wechatpayinterface()
    {
        $param = I('params');

        require_once(dirname(dirname(dirname(__FILE__))) . '/Notify/wx/wxcontroller.php');
        $wecontroller = new wecontroller();
        $wechat_user = $wecontroller->authlogin();

        $orderno = $param['order_id'];

        $investinfo = M("Invest")->where(array("order_no" => $orderno))->find();

        $attributes = [
            'openid' => $wechat_user['openid'],
            'trade_type' => 'APP', // JSAPI，NATIVE，APP...
            'body' => "水果团购" . $orderno . "批次商品",
            'detail' => "水果团购" . $orderno . "批次商品",
            'out_trade_no' => $orderno,
            'spbill_create_ip' => $_SERVER['REMOTE_ADDR'],
            'total_fee' => $investinfo['amount'] * 100,    //付款金额
        ];
        require_once(dirname(dirname(dirname(__FILE__))) . '/Notify/wx/pay.php');
        $wechatpay = new wechatpay();
        $returninfo = json_decode($wechatpay->wepay($attributes), true);
        $this->ajaxReturn(array('error' => 0, 'info' => $returninfo));
    }
    //支付宝支付
    public function alipayinterface()
    {
        $param = I('params');
        $orderid = $param['invest_id'];
        $investinfo = M("Invest")->where(array("id" => $orderid))->find();
        require_once(dirname(dirname(dirname(__FILE__))) . '/Notify/alipay/alipay.config.php');
        require_once(dirname(dirname(dirname(__FILE__))) . '/Notify/alipay/lib/alipay_submit.class.php');
        //构造要请求的参数数组，无需改动
        $parameter = array(
            "service"       => $alipay_config['service'],
            "partner"       => $alipay_config['partner'],
            "seller_id"  => $alipay_config['seller_id'],
            "payment_type" => $alipay_config['payment_type'],
            "notify_url"	=> $alipay_config['notify_url'],
            "return_url"	=> $alipay_config['return_url'],

            "anti_phishing_key"=>$alipay_config['anti_phishing_key'],
            "exter_invoke_ip"=>$alipay_config['exter_invoke_ip'],
            "out_trade_no"	=> $investinfo["order_no"],
            "subject"	=> "水果团购订单",
            "total_fee"	=> $investinfo['amount'],
            "body"	=> "水果团购订单",
            "_input_charset"	=> trim(strtolower($alipay_config['input_charset']))
        );
        $alipaySubmit = new AlipaySubmit($alipay_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认");
        echo $html_text;
    }
}